﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ODT.PowerPmacComLib;
using ODT.Common.Core;

namespace PPPlotControl
{
    public partial class Form_TerminalParameter : Form
    {
        private ISyncTerminalCommunicationInterface TelnetGather;
        private ISyncGpasciiCommunicationInterface TelnetGPAscii;
        private deviceProperties currentAddress = new deviceProperties();

		public bool IsConnected
		{
			get
			{
				if (TelnetGather.SocketConnected)
				{
					return TelnetGPAscii.GpAsciiConnected;
				}
				return false;
			}
		}

		public Form_TerminalParameter()
        {
            InitializeComponent();

			this.StartPosition = FormStartPosition.CenterScreen;
            this.Size = new System.Drawing.Size(550, 480);
			this.dataGridView1.AutoSize = true;

			this.dataGridView1.CellEndEdit += DataGridView1_CellEndEdit; 
			this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
			this.dataGridView1.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
		}

		private bool GetValue(string key, out double value)
		{
			value = 0;
			if (String.IsNullOrEmpty(key)) return false;

			string response;
			TelnetGPAscii.GetResponse(key, out response, 0);
			response = response.Trim('\u0006', '\r', '\n');
			if (response.Contains("stdin"))
			{
				MessageBox.Show($"无效的参数, {key}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

			string[] array = response.Split(new char[1] { '=' }, StringSplitOptions.RemoveEmptyEntries);
			if (array.Length <= 0)
			{
				MessageBox.Show($"无效的参数, {key}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

			response = array[array.Length - 1];
			if (!Double.TryParse(response, out value))
			{
				MessageBox.Show("${key} 值错误", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}
			
			return true;
		}

        private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
			var RowIndex = e.RowIndex;
			var ColumnIndex = e.ColumnIndex;
			if (ColumnIndex > 0) return;

			if (!IsConnected) return;

			string key = this.dataGridView1.Rows[RowIndex].Cells[ColumnIndex].Value.ToString();
			double value;
			if (GetValue(key, out value))
            {
				this.dataGridView1.Rows[RowIndex].Cells[1].Value = value;
			}
		}

        private void Form_TerminalParameter_Load(object sender, EventArgs e)
        {
            currentAddress.SetProperties(DeviceConnectionSettings.DefaultSettings);
			ConnectDeviceCommunication();

            this.dataGridView1.Rows.Clear();

            string filePath = System.Environment.CurrentDirectory + "\\parameter.txt";
            if (!File.Exists(filePath)) return;

            using (StreamReader reader = new StreamReader(filePath))
            {
                do
                {
                    if (reader.EndOfStream) break;

                    var str = reader.ReadLine().Trim();
                    if (String.IsNullOrEmpty(str))
                    {
                        continue;
                    }

                    this.dataGridView1.Rows.Add(str, 0);

                } while (true);
            }

            this.dataGridView1.ResumeLayout();
        }

        private void Form_TerminalParameter_FormClosed(object sender, FormClosedEventArgs e)
        {
			DisconnectClient();

			string filePath = System.Environment.CurrentDirectory + "\\parameter.txt";
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
                {
                    writer.WriteLine(this.dataGridView1.Rows[i].Cells[0].Value.ToString());
                }
            }
        }

        private void buttonToPMAC_Click(object sender, EventArgs e)
        {
			if (!IsConnected) return;

			for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
			{
				string key = this.dataGridView1.Rows[i].Cells[0].Value.ToString();
				if (String.IsNullOrEmpty(key)) continue;

				var str = this.dataGridView1.Rows[i].Cells[1].Value.ToString();
				if (String.IsNullOrEmpty(str)) continue;

				double value;
				if (!Double.TryParse(str, out value))
				{
					continue;
				}
				string cmd = String.Format($"{key}={value}");
				
				string response;
				TelnetGPAscii.GetResponse(cmd, out response, 0);
			}

			MessageBox.Show("写入完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void buttonFromPMAC_Click(object sender, EventArgs e)
        {
			if (!IsConnected) return;

			for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
			{
				string key = this.dataGridView1.Rows[i].Cells[0].Value.ToString();
				double value;
				if (GetValue(key, out value))
                {
					this.dataGridView1.Rows[i].Cells[1].Value = value;
				}
			}

			MessageBox.Show("读取完成！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
		}

		public bool ConnectDeviceCommunication()
		{
			bool flag = false;
			bool flag2 = false;
			if (currentAddress.IPAddress.IsNoDevice)
			{
				return true;
			}
			WaitCursor waitCursor = new WaitCursor();
			try
			{
				TelnetGPAscii = TelnetGPAscii ?? new DTCommunication();
				TelnetGather = TelnetGather ?? new TelnetTerminal();
				flag = TelnetGather.ConnectTerminal(currentAddress.IPAddress, currentAddress.PortNumber, currentAddress.User, currentAddress.Password);
				flag2 = TelnetGPAscii.ConnectGpAscii(currentAddress.IPAddress, currentAddress.PortNumber, currentAddress.User, currentAddress.Password);
			}
			catch (Exception ex)
			{
			}
			finally
			{
				waitCursor.Dispose();
			}
			return flag && flag2;
		}

		public void DisconnectClient()
		{
			if (TelnetGather == null || TelnetGPAscii == null)
			{
				return;
			}
			try
			{
				if (IsConnected)
				{
					TelnetGPAscii.DisconnectGpascii();
					TelnetGather.DisconnectTerminal();
				}
			}
			catch (Exception ex)
			{
			}
			finally
			{
			}
		}
	}
}
